package 学习计划.数据结构;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 会玩的洋洋
 * https://leetcode.cn/problems/design-hashmap/?envType=study-plan&id=shu-ju-jie-gou-ji-chu&plan=data-structures&plan_progress=cqjfoh6
 */
public class _706_设计哈希映射 {

}

/**
 * 执行用时：17ms，内存消耗：48.3MB
 */
class MyHashMap {
    private static class Node {
        private int key;
        private int value;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public int getKey() {
            return this.key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

    private static final int BASE = 769;
    private LinkedList[] data;

    public MyHashMap() {
        data = new LinkedList[BASE];
        for (int i = 0; i < BASE; i++) {
            data[i] = new LinkedList<Node>();
        }
    }

    public void put(int key, int value) {
        int hash = calcHash(key);
        Iterator<Node> iterator = data[hash].iterator();
        while (iterator.hasNext()) {
            Node temp = iterator.next();
            if (temp.getKey() == key) {
                temp.setValue(value);
                return;
            }
        }
        data[hash].offerLast(new Node(key, value));
    }

    public int get(int key) {
        int hash = calcHash(key);
        Iterator<Node> iterator = data[hash].iterator();
        while (iterator.hasNext()) {
            Node node = iterator.next();
            if (node.getKey() == key) {
                return node.getValue();
            }
        }
        return -1;
    }

    public void remove(int key) {
        int hash = calcHash(key);
        Iterator<Node> iterator = data[hash].iterator();
        while (iterator.hasNext()) {
            Node node = iterator.next();
            if (node.getKey() == key) {
                data[hash].remove(node);
                return;
            }
        }
    }

    private int calcHash(int key) {
        return key % BASE;
    }
}
